// ignore_for_file: avoid_init_to_null

import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'dart:math' as math;
import 'dart:typed_data';
import 'dart:ui' as ui;

// import 'package:fl_baidu_mob_stat_ys/fl_baidu_mob_stat_ys.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/navigation/navigation_logic.dart';
import 'package:ball_lion/entity/match/expert_views_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/server/api/other_api.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/utils/sp_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/mine/my_web_page.dart';
// import 'package:umeng_common_sdk/umeng_common_sdk.dart';
import 'package:url_launcher/url_launcher_string.dart';

class Utils {
  static double dp(double dpValue, BuildContext context) {
    return dpValue * MediaQuery.of(context).devicePixelRatio;
  }

  static String getImgPath(String name) {
    return 'assets/image/$name';
  }

  static String getFilePath(String name) {
    return 'assets/file/$name';
  }

  static String getSoundPath(String name) {
    return 'assets/sound/$name.mp3';
  }

  //生成随机字符串
  static String getRandomString(int length) {
    final random = math.Random();
    const availableChars =
        'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
    final randomString = List.generate(length,
            (index) => availableChars[random.nextInt(availableChars.length)])
        .join();
    return randomString;
  }

  static Future login({bool dialog = false}) async {
    Get.toNamed(Routes.login);
    // try {
    //   await Get.find<UmengService>()
    //       .login(LoginType.login, userId: User.auth?.userId, dialog: dialog);
    // } catch (e) {
    //   if (e == "600002") {
    //     await Get.find<UmengService>()
    //         .login(LoginType.login, userId: User.auth?.userId, dialog: dialog);
    //   }
    //   Toast.text("登录遇到问题请稍后再试");
    // }
  }

  //日期格式化
  static String formatTime(int timestamp) {
    int interval = DateTime.now().millisecondsSinceEpoch - timestamp;
    if (interval < 60 * 1000) {
      interval = interval ~/ 1000;
      return '$interval秒前';
    } else if (interval < 60 * 60 * 1000) {
      interval = interval ~/ 60000;
      return '$interval分钟前';
    } else if (interval < 24 * 60 * 60 * 1000) {
      interval = interval ~/ 3600000;
      return '$interval小时前';
    } else if (interval < 3 * 24 * 60 * 60 * 1000) {
      interval = interval ~/ (3600000 * 24);
      return '$interval天前';
    } else {
      return DateTimeUtils.formatTimeStamp(timestamp, 'MM-dd HH:mm');
    }
  }

  static FutureOr<T?> tryOrNullf<T>(FutureOr<T> Function() fn) async {
    try {
      return await fn();
    } catch (err) {
      log("$err");
      return null;
    }
  }

  static String zanNum(int num) {
    if (num < 10000) {
      return "$num";
    }
    return "${num ~/ 10000}万+";
  }

  static String numLimit(int v, {int limit = 99}) {
    if (v <= limit) {
      return "$v";
    }
    return "$limit+";
  }

  static Future doJump(String routestr) async {
    String ref = routestr;
    try {
      ref = String.fromCharCodes(base64Decode(ref));
    } catch (err) {}

    if (RegExp("^http[s]?://").hasMatch(ref)) {
      Get.toNamed(
        Routes.webview,
        arguments:
            WebPara(ref, header: {'Authorization': User.auth?.token ?? ''}),
        preventDuplicates: false,
      );
    }

    log("do jump setp 2");
    jumpWithJsonStr(ref);
  }

  // static String _resolvePath(String path) {
  //   final topPath = {
  //     '/home': '首页',
  //     '/match': '比赛',
  //     '/expert': "推荐",
  //     '/data': '数据',
  //     '/my': '我的'
  //   };
  //   return topPath[path] ?? path;
  // }

  static jumpWithJsonStr(String source) {
    log(Get.currentRoute);
    try {
      final map = jsonDecode(source);
      String path = map['path']! as String;
      final arguments = map['arguments'];
      int? inApp = map['inApp'];
      Map<String, String>? params;
      if (map['params'] != null) {
        params = map['params']!.cast<String, String>();
      }
      // path = _resolvePath(path);
      if (path.startsWith("/")) {
        if (NavigationLogic.homeRoutes.contains(path)) {
          if (Get.currentRoute != Routes.navigation) {
            Get.until((route) => Get.currentRoute == Routes.navigation);
          }
          Get.find<NavigationLogic>()
              .doJump(path, arguments: arguments, parameters: params);
        } else {
          Routes.toPage(path,
              arguments: arguments,
              parameters: params,
              preventDuplicates: false);
        }
      } else if (RegExp("^http[s]?://").hasMatch(path)) {
        if (inApp == 0) {
          launchUrlString(path,
              mode: LaunchMode.externalApplication,
              webViewConfiguration: WebViewConfiguration(
                  enableDomStorage: false,
                  headers: {'Authorization': User.auth?.token ?? ''}));
        } else {
          Get.toNamed(Routes.webview,
              arguments: WebPara(path,
                  header: {'Authorization': User.auth?.token ?? ''}),
              parameters: params);
        }
      }
    } catch (err) {
      log("json jump err $err");
    }
  }

  static onEvent(String eventId, {Map<String, dynamic>? params}) async {
    // log('友盟统计埋点============ eventId = $eventId,  params = $params');
    Map<String, String>? paramJson;
    if (params != null) {
      paramJson = {
        for (var i = 0; i < params.keys.length; i++)
          "param${i + 1}": params[params.keys.toList()[i]].toString(),
      };
    }

    // try {
    //   UmengCommonSdk.onEvent(eventId, paramJson != null ? paramJson : {});
    // } catch (e) {
    //   log("友盟埋点报错");
    // }
    OtherApi.uploadEvent(eventId, params: paramJson);
    // EventDio.postEvent(eventId, params: params?.values.toList());
  }

  static pageStart(String? route) async {
    if (route != null && SpUtils.agreePrivacy == true) {
      // EventDio.postEvent("page_enter");
      OtherApi.uploadEvent('page_enter');
    }
  }

  static pageEnd(String? route) {
    if (route != null && SpUtils.agreePrivacy == true) {
      // EventDio.postEvent("page_exit");
      OtherApi.uploadEvent('page_exit');
    }
  }

  static String bbPositionName(String? position) {
    switch (position) {
      case "C":
        return "中锋";
      case "SF":
        return "小前锋";
      case "PF":
        return "大前锋";
      case "SG":
        return "得分后卫";
      case "PG":
        return "组织后卫";
      case "F":
        return "前锋";
      case "G":
        return "后卫";
      default:
        return "";
    }
  }

  /// 2020-2021 转 20/21
  static String parseYear(String year) {
    String yearStr = year;
    if (yearStr.length > 4) {
      yearStr = '${yearStr.substring(2, 4)}/${yearStr.substring(7, 9)}';
    }
    return yearStr;
  }

  // static int? get getGetxIntId => () {
  //       final id = int.tryParse(Get.parameters['id'] ?? "");
  //       log("get Getx Int id = $id");
  //       if (id != null) {
  //         return id;
  //       }
  //       if (Get.arguments is int) {
  //         return Get.arguments as int;
  //       } else {
  //         return null;
  //       }
  //     }.call();
  static String? get getGetxStringId =>
      Get.parameters['id'] ??
      () {
        if (Get.arguments is String) {
          return Get.arguments as String;
        }
      }.call();

  ///足球是否在比赛中
  static bool isSoccerMatchBegin(String? status) {
    if (status == '2' ||
        status == '3' ||
        status == '4' ||
        status == '5' ||
        status == '6') {
      return true;
    } else {
      return false;
    }
  }

  // ///足球比赛结束或意外
  // static bool isSoccerMatchEnd(String? status) {
  //   if (status == '2' ||
  //       status == '3' ||
  //       status == '4' ||
  //       status == '5' ||
  //       status == '6') {
  //     return true;
  //   } else {
  //     return false;
  //   }
  // }

  static Widget divider() => const Divider(height: 0.5, color: Colours.greyEE);

  // static share() async {
  //   String url = 'https://www.qiuxiangbiao.com/mp/h5/qxb.html?id=c11011';
  //   String title = '分享给你一个看比赛和数据的APP';
  //   String content = '看比分、看数据、看专家推荐，就来球狮体育！';
  //   String logoUrl = 'https://oss.qiuxiangbiao.com/prod/resource/qxb_logo.png';
  //   final jsonStr = Get.find<ResourceService>().inviteConfig?.content;
  //   if (jsonStr != null) {
  //     final json = jsonDecode(jsonStr);
  //     url = json['url'];
  //     title = json['title'];
  //     content = json['content'];
  //     logoUrl = json['logo'];
  //   }
  //   final File logo = await DefaultCacheManager().getSingleFile(logoUrl);
  //   // String imageUri =
  //   //     'https://oss.qiuxiangbiao.com/prod/resource/qxb_logo.png';
  //   final ByteData bytes =
  //       await rootBundle.load(Utils.getImgPath('qxb_logo.png'));
  //   final Uint8List thumbImage = bytes.buffer.asUint8List();
  //   ShareBottomSheet.show(onShareWx: () {
  //     // WechatKitPlatform.instance.shareWebpage(
  //     //     scene: WechatScene.SESSION,
  //     //     title: title,
  //     //     description: content,
  //     //     thumbData: thumbImage,
  //     //     webpageUrl: url);
  //     // getCoupon();
  //   }, onShareTimeline: () {
  //     // WechatKitPlatform.instance.shareWebpage(
  //     //     scene: WechatScene.TIMELINE,
  //     //     title: title,
  //     //     description: content,
  //     //     thumbData: thumbImage,
  //     //     webpageUrl: url);
  //     // getCoupon();
  //   }, onShareQQ: () async {
  //     // TencentKitPlatform.instance.shareWebpage(
  //     //     scene: TencentScene.SCENE_QQ,
  //     //     title: title,
  //     //     summary: content,
  //     //     appName: '球狮体育',
  //     //     imageUri: Uri.file(logo.path),
  //     //     targetUrl: url);
  //     // getCoupon();
  //   }, onShareQQZone: () async {
  //     // TencentKitPlatform.instance.shareWebpage(
  //     //     scene: TencentScene.SCENE_QZONE,
  //     //     title: title,
  //     //     summary: content,
  //     //     appName: '球狮体育',
  //     //     imageUri: Uri.file(logo.path),
  //     //     targetUrl: url);
  //     // getCoupon();
  //   }, onShareWb: () async {
  //     // WeiboKitPlatform.instance.shareWebpage(
  //     //     thumbData: thumbImage,
  //     //     title: title,
  //     //     description: content,
  //     //     webpageUrl: url);
  //     // getCoupon();
  //   });
  // }
}

typedef FilterFn<T> = bool Function(T item);

extension ListEx1<T> on List<T> {
  List<T> filter(FilterFn<T> fn) {
    List<T> l = [];
    for (var element in this) {
      if (fn(element)) {
        l.add(element);
      }
    }
    return l;
  }

  List<T>? filterOrNull(FilterFn<T> fn) {
    final l = filter(fn);
    if (l.isEmpty) {
      return null;
    }
    return l;
  }

  List<T> replaceAll(Iterable<T> replacements) {
    replaceRange(0, length, replacements);
    return this;
  }

  List<T> insertWith(int? index, Iterable<T> replacements) {
    if (index != null) {
      insertAll(index, replacements);
    }
    return this;
  }

  List<List<T>> splitEvery(int count) {
    if (length > count) {
      List<List<T>> list = [];
      List<T> slice = deepCopy;
      var total = length;
      while (total > count) {
        list.add(slice.sublist(0, count));
        slice.removeRange(0, count);
        total -= count;
      }
      if (slice.hasValue) list.add(slice);
      return list;
    } else {
      return [this];
    }
  }

  List<T> insertEvery(T element) {
    for (var i = 1; i < length; i += 2) {
      insert(i, element);
    }
    return this;
  }

  List<T> get deepCopy {
    return List.generate(length, (index) => this[index]);
  }

  List<int> indexOn(List<T> list) {
    List<int> indexs = [];
    for (var element in list) {
      int i = indexOf(element);
      if (i != -1) indexs.add(i);
    }
    indexs.sort();
    return indexs;
  }

  List<T> append(T element) {
    add(element);
    return this;
  }
}

extension ListExtension on List? {
  bool get hasValue => this != null && this!.isNotEmpty;
  bool get noValue => this == null || this!.isEmpty;
}

extension ListNumExtension on List<num?> {
  num? max() {
    num? value;
    if (length >= 2) {
      value = this[length - 1];
      for (var i = length - 1; i > 0; i--) {
        if (value! < this[i - 1]!) value = this[i - 1];
      }
    } else if (length != 0) {
      value = this[0];
    }
    return value;
  }

  num? min() {
    num? value;
    if (length >= 2) {
      value = this[length - 1];
      for (var i = length - 1; i > 0; i--) {
        if (value! > this[i - 1]!) value = this[i - 1];
      }
    } else if (length != 0) {
      value = this[0];
    }
    return value;
  }
}

extension IntExtension on int? {
  bool get hasValue => this != null && this != 0;
  String get toChn {
    List<String> list = [];
    List<String> chn = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
    if (this == null) return "";
    toString().split("").forEach((element) {
      list.add(chn[element.toInt()!]);
    });
    return list.join();
  }
}

extension StringExtension on String? {
  bool get hasValue => this != null && this!.isNotEmpty;
  bool get noValue => this == null || this == '';
  int? toInt() {
    if (this == null) {
      return null;
    } else {
      return int.tryParse(this!);
    }
  }

  double? toDouble() {
    if (this == null) {
      return null;
    } else {
      return double.tryParse(this!);
    }
  }

  DateTime? get time {
    if (this == null) {
      return null;
    } else {
      return DateTime.tryParse(this!);
    }
  }
}

extension StringEx1 on String {
  String get changeUnit => replaceAll("球币", "球币");
  String lastString(int len) =>
      substring((length - len) > 0 ? (length - len) : 0, length);
}

extension ScaffoldTopTouch on Scaffold {
  Widget topTouch(FutureOr Function() tap) {
    return Stack(
      children: [
        this,
        Positioned(
            top: 0,
            // bottom: 0,
            left: 0,
            right: 0,
            child: Container(
              height: 20,
              color: Colors.blue,
            )).tap(() {
          tap.call();
        }),
      ],
    );
  }
}

extension PlanExtension on List<PlanEntity> {
  List<List<PlanEntity>> get foldPlans {
    List<List<PlanEntity>> list = [];
    if (isEmpty) {
      return [];
    }
    List<int> spot = [];
    var sportsId = this[0].sportsId;
    var expertId = this[0].expertId;
    for (var i = 0; i < length; i++) {
      if (this[i].sportsId != sportsId || this[i].expertId != expertId) {
        spot.add(i);
        sportsId = this[i].sportsId;
        expertId = this[i].expertId;
      }
    }
    if (spot.length > 1) {
      list.add(sublist(0, spot[0]));
      list.addAll(List.generate(spot.length, (index) {
        if (index == spot.length - 1) return sublist(spot.last, length);
        return sublist(spot[index], spot[index + 1]);
      }));
    } else if (spot.length == 1) {
      list.add(sublist(0, spot[0]));
      list.add(sublist(spot[0], length));
    } else {
      list.add(this);
    }
    return list;
  }
}

// extension DoubleExtension on double {
//   String get toStringFlex{
//     var list = toString().split(".");
//     if(list.length != 1){
//       for(var i == 0)
//     }
//   }
// }

extension GlobalExtension on GlobalKey {
  RenderRepaintBoundary? get getBoundary {
    final boundary = currentContext?.findRenderObject();
    if (boundary != null && boundary is RenderRepaintBoundary) {
      return boundary;
    } else {
      return null;
    }
  }
}

extension RefreshExtension on IndicatorMode? {
  bool get isIdle => this == null || this == IndicatorMode.inactive;
}
